package cn.myapps.demospringsecurity.manager;

import cn.myapps.demospringsecurity.entity.LoginUser;
import cn.myapps.demospringsecurity.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 自定义认证
 */
@Component
public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    PasswordEncoder passwordEncoder;
    private final UserDetailsServiceImpl userDetailsService;

    public CustomAuthenticationManager(UserDetailsServiceImpl userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        // 1. 加载用户
        LoginUser userDetails = (LoginUser) userDetailsService.loadUserByUsername(username);
        passwordEncoder.encode(password);
        // 2. 校验密码
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }

        // 3. 返回认证信息
        return new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities()
        );
    }
}